package io.github.lee.app.unsplash.ui.search.result.photo

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.chad.library.adapter.base.util.setOnDebouncedItemClick
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.ui.detail.photo.PhotoDetailActivity
import io.github.lee.app.unsplash.ui.search.result.ISearchAction
import io.github.lee.app.unsplash.views.LoadStateAdapter
import io.github.lee.core.ui.BaseRefreshFragment

@AndroidEntryPoint
class ResultPhotoFragment : BaseRefreshFragment<ResultPhotoVM>(), ISearchAction {

    companion object {
        fun newInstance(): ResultPhotoFragment = ResultPhotoFragment()
    }

    //===Desc:======================================================================================
    override fun onCreateViewModel(): ResultPhotoVM =
        viewModels<ResultPhotoVM>().value

    override fun onCreateTrailingLoadAdapter(): TrailingLoadStateAdapter<*> =
        LoadStateAdapter()

    override fun onCreateLayoutManager(): RecyclerView.LayoutManager =
        StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            .also {
                it.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
            }

    //===Desc:======================================================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        enableRefresh = false
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
        vm?.adapter?.setOnDebouncedItemClick { adapter, _, position ->
            PhotoDetailActivity.start(mContext, adapter.items[position])
        }
    }

    override fun search(keyword: String) {
        refreshLayout?.isRefreshing = true
        vm?.searchKeyword = keyword
        vm?.onRefreshOrLoadMore(true)
    }


}